package ui

import (
	"strings"

	"github.com/lxn/walk"
)

// TempVar 临时变量类型
type TempVar struct {
	Name  string
	Value string
}

// TempVarModel 临时变量表格模型
type TempVarModel struct {
	walk.TableModelBase
	vars []TempVar
}

func NewTempVarModel(vars []TempVar) *TempVarModel {
	return &TempVarModel{vars: vars}
}

func (m *TempVarModel) RowCount() int {
	return len(m.vars)
}

func (m *TempVarModel) Value(row, col int) interface{} {
	v := m.vars[row]
	switch col {
	case 0:
		return v.Name
	case 1:
		return v.Value
	}
	return nil
}

// TempVarManager 临时变量管理器
type TempVarManager struct {
	vars []TempVar
}

func NewTempVarManager() *TempVarManager {
	return &TempVarManager{
		vars: make([]TempVar, 0),
	}
}

func (m *TempVarManager) ReplaceVars(url string) string {
	for _, v := range m.vars {
		url = strings.ReplaceAll(url, "${"+v.Name+"}", v.Value)
	}
	return url
}

// 添加获取变量列表的方法
func (m *TempVarManager) GetVars() []TempVar {
	return m.vars
}

// 添加或更新变量
func (m *TempVarManager) AddOrUpdateVar(name, value string) {
	for i, v := range m.vars {
		if v.Name == name {
			m.vars[i].Value = value
			return
		}
	}
	m.vars = append(m.vars, TempVar{Name: name, Value: value})
}

// DeleteVar 删除指定名称的变量
func (m *TempVarManager) DeleteVar(name string) bool {
	for i, v := range m.vars {
		if v.Name == name {
			m.vars = append(m.vars[:i], m.vars[i+1:]...)
			return true
		}
	}
	return false
}
